<template>
  <button
    type="primary"
    :params="{ token, tenantId, api }"
    :change:params="uploadModule.params"
    size="mini"
    @click="uploadModule.onClick"
  >
    选择文件
  </button>
</template>

<script>
import cache from '@/utils/cache';
export default {
  data() {
    return {
      token: '',
      tenantId: '',
      // api: 'https://testappthwater.thwater.com:30080/api/oss/sysOss/upload',
      api: import.meta.env.VITE_SERVER_BASEURL + '/oss/sysOss/upload',
    };
  },
  methods: {
    uploadProgress(progress) {
      if (progress === 'begin') {
        uni.showLoading({
          title: '上传中',
          mask: true,
        });
      } else if (progress === 'fail') {
        uni.hideLoading();
        uni.showToast({
          title: '上传失败',
          mask: true,
        });
      } else {
        uni.showLoading({
          title: `已上传${progress}%`,
          mask: true,
        });
      }
    },
    uploadComplete(data) {
      uni.hideLoading();
      uni.showToast({
        title: '上传成功',
      });
      this.$emit('complete', data);
    },
  },
  mounted() {
    this.token = cache.get('token');
    this.tenantId = cache.get('tenantId');
    // this.api = BASEURL + '/oss/sysOss/upload';
  },
};
</script>
<script module="uploadModule" lang="renderjs">
export default {
	data() {
		return {
			token: '',
			tenantId: '',
			api: ''
		}
	},
	methods: {
		params(newValue) {
			const {
				token,
				tenantId,
				api
			} = newValue;
			this.token = token;
			this.tenantId = tenantId;
			this.api = api
		},
		onClick(event, ownerInstance) {
			let fileInputDom = document.createElement("input");
			fileInputDom.setAttribute('type', 'file');
			fileInputDom.setAttribute('accept', '*');

			fileInputDom.click();
			fileInputDom.addEventListener('change', (e) => {
				fileInputDom = null;
				const file = e.target.files[0];
				const formData = new FormData();
				formData.append('file', file);

				const xhr = new XMLHttpRequest();
				xhr.open('POST', this.api, true);
				xhr.setRequestHeader('Authorization', 'Bearer ' + this.token);
				xhr.setRequestHeader('Tenant-Id', this.tenantId);

				xhr.upload.addEventListener(
					'progress',
					(event) => {
						if (event.lengthComputable) {
							let percent = Math.ceil((event.loaded * 100) / event.total);
							if (percent <= 100) {
								ownerInstance.callMethod('uploadProgress', percent)
							}
						}
					},
					false,
				);

				xhr.ontimeout = function() {
					ownerInstance.callMethod('uploadProgress', 'fail')
					e.target.value = '';
				};

				xhr.onreadystatechange = (ev) => {
					if (xhr.readyState == 4) {
						if (xhr.status == 200) {
							const res = JSON.parse(xhr.responseText);
							ownerInstance.callMethod('uploadComplete', res.data)
							e.target.value = '';
							return;
						} else {
							e.target.value = '';
						}
					}
				};

				xhr.send(formData);
				ownerInstance.callMethod('uploadProgress', 'begin')
			})
		}
	},
}
</script>
<style></style>
